import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
declare const go: any;

@Component({
    selector: 'app-intelligentdiagnosis',
    templateUrl: './intelligentdiagnosis.component.html',
    styleUrls: ['./intelligentdiagnosis.component.less']
})

export class IntelligentDiagnosisComponent implements OnInit {
    themeClass = 'whitetheme';
    myDiagram: any;
    clickObj: any;
    flowCharList = [
        // { "parent": "", "key": "1", "name": "转辙机故障曲线分析", "child": "0", "lock": "0", "remark": "", "trueKey": "2", "falseKey": "", "width": "15", "height": "4", "category": "oval" },
        // { "parent": "1", "key": "2", "name": "是否有熔丝报警", "child": "0", "lock": "0", "remark": "", "trueKey": "100", "falseKey": "101", "greater": "", "equal": "", "less": "" },

        // { "parent": "2", "key": "100", "name": "报警", "child": "3,4,5", "describe": "1.三项电流Ia,Ib,Ic = 0 \n 2.电流曲线<=1.2秒内，Ia,Ib,Ic任意两项电流远大于5A（异常 高） \n 3.14秒内，Ia,Ib,Ic任意两项电流远大于5A（异常高）", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "greater": "", "equal": "", "less": "" },
        // { "parent": "2", "key": "101", "name": "未报警", "child": "0", "lock": "0", "remark": "", "trueKey": "102", "falseKey": "", "greater": "1.2", "equal": "", "less": "0.2" },

        // { "parent": "100", "key": "3", "name": "三项电流Ia,Ib,Ic = 0", "child": "0", "lock": "0", "remark": "", "trueKey": "6", "falseKey": "7", "greater": "", "equal": "", "less": "" },
        // { "parent": "100", "key": "4", "name": "电流曲线<=1.2秒内，Ia,Ib,Ic \n 任意两项电流远大于5A（异常 高）", "child": "0", "lock": "0", "remark": "", "trueKey": "8", "falseKey": "9", "greater": "", "equal": "", "less": "" },
        // { "parent": "100", "key": "5", "name": "14秒内，Ia,Ib,Ic任意两项电 \n 流远大于5A（异常高）", "child": "0", "lock": "0", "remark": "", "trueKey": "10", "falseKey": "11", "greater": "", "equal": "", "less": "" },

        // { "parent": "3", "key": "6", "name": "启动空开跳闸", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "greater": "", "equal": "", "less": "", "category": "diamond" },
        // { "parent": "3", "key": "7", "name": "断路器断开", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "greater": "", "equal": "", "less": "", "category": "diamond" },
        // { "parent": "4", "key": "8", "name": "启动空开跳闸，启动电路短路", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "width": "22", "greater": "", "equal": "", "less": "", "category": "diamond" },
        // { "parent": "4", "key": "9", "name": "断路器断开", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "greater": "", "equal": "", "less": "", "category": "diamond" },
        // { "parent": "5", "key": "10", "name": "启动空开跳闸，室外启动电路短路", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "width": "22", "greater": "", "equal": "", "less": "", "category": "diamond" },
        // { "parent": "5", "key": "11", "name": "断路器断开", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "greater": "", "equal": "", "less": "", "category": "diamond" },

        // { "parent": "101", "key": "102", "name": "1.电流曲线在[0.2秒，1.2秒]间, \n 三项电流 1.2A <=Ia,Ib,Ic \n 2.电流曲线在>=1.2秒, \n Ia,Ib,Ic = 0A", "child": "0", "lock": "0", "remark": "", "trueKey": "", "falseKey": "", "width": "26", "height": "20", "greater": "", "equal": "", "less": "", "category": "diamond" }

        { "parent": "", "key": "101", "name": "进路操作意图进路所闭", "remark": "", "describe": "始终端按钮按下", "width": "16", "height": "4", "trueKey": "102", "category": "oval", "lock": "0", "child": "0" },
        { "parent": "101", "key": "102", "name": "列车信号机未开放", "remark": "", "describe": "1.进路锁闭5S后未开放\n2.进路未锁闭，终端按钮按下后，1分钟循环判", "width": "16", "height": "10", "trueKey": "106", "falseKey": "105", "greater": "", "greaterEqual": "", "equal": "5", "lessEqual": "", "less": "60", "lock": "0", "child": "0" },
        { "parent": "102", "key": "105", "name": "Exit", "remark": "", "width": "6", "height": "4", "trueKey": "", "falseKey": "", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "category": "diamond", "lock": "0", "child": "0" },
        { "parent": "102", "key": "106", "name": "满足闭塞条件（闭塞灯-L亮）", "remark": "", "width": "25", "height": "8", "trueKey": "110", "falseKey": "109", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "lock": "0", "child": "0" },
        { "parent": "106", "key": "109", "name": "闭塞条件不具备", "remark": "", "width": "12", "height": "8", "trueKey": "", "falseKey": "", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "category": "diamond", "lock": "0", "child": "0" },
        { "parent": "106", "key": "110", "name": "LXJ吸起", "remark": "", "width": "12", "height": "6", "trueKey": "114", "falseKey": "113", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "lock": "0", "child": "0" },
        { "parent": "110", "key": "113", "name": "LXJ未吸起", "remark": "", "width": "10", "height": "8", "trueKey": "", "falseKey": "", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "category": "diamond", "lock": "0", "child": "0" },
        { "parent": "110", "key": "114", "name": "点灯电压对应开关量吸起", "remark": "", "width": "18", "height": "10", "trueKey": "118", "falseKey": "117", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "lock": "0", "child": "0" },
        { "parent": "114", "key": "117", "name": "室内开路", "remark": "", "width": "10", "height": "8", "trueKey": "", "falseKey": "", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "category": "diamond", "lock": "0", "child": "0" },
        { "parent": "114", "key": "118", "name": "室外开路", "remark": "", "width": "10", "height": "8", "trueKey": "", "falseKey": "", "greater": "", "greaterEqual": "", "equal": "", "lessEqual": "", "less": "", "category": "diamond", "lock": "0", "child": "0" }
    ];
    recoveryData: any = [
        // { "key": "1", "trueKey": "2" },
        // { "key": "2", "trueKey": "100" },
        // { "key": "100", "child": "4,5" },
        // { "key": "4", "trueKey": "8" },
        // { "key": "8" },
        // { "key": "5", "falseKey": "11" },
        // { "key": "11" }
    ];
    cid = [];
    stroke = '#ddd';
    fill = '#ddd';
    color = '#000';
    arrow = '#7bf4e3';
    green1 = '#c0f8f0';
    green2 = '#7bfae8';
    blue1 = '#cae3f9';
    blue2 = '#7cc0fa';
    // modal
    Visible = false;
    operaStatus = false;
    popText = '';
    popInput: any;
    innerHeight = window.innerHeight;

    constructor(public msg: NzMessageService) { }

    ngOnInit() {
        this.goflow();
    }
    themeChenge(e) {
        this.themeClass = e;
    }
    goflow() {
        const $ = go.GraphObject.make;
        if (this.myDiagram) {
            this.myDiagram.div = null;
        }
        this.myDiagram =
            $(go.Diagram, 'myDiagramDiv', {
                "animationManager.isEnabled": false, // 禁止画布初始化动画  
                initialContentAlignment: go.Spot.Center, // 自适应居中
                "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom, // 鼠标滚动 
                layout: $(go.TreeLayout, {
                    angle: 90
                })
            });

        this.myDiagram.nodeTemplate =
            $(go.Node, 'Auto',
                { mouseEnter: this.mouseEnter }, // 线的鼠标移入事件
                {
                    locationSpot: go.Spot.Center,
                    fromSpot: go.Spot.AllSides,
                    toSpot: go.Spot.AllSides
                },
                $(go.Shape, 'RoundedRectangle',
                    {
                        name: 'SHAPE',
                        strokeWidth: 2,
                        stroke: this.stroke,
                        fill: this.fill
                    }
                ),
                $(go.TextBlock,
                    {
                        stroke: this.color,
                        margin: 5
                    },
                    new go.Binding('text', 'name')
                ),
                {
                    click: (ev, obj) => {
                        this.categoryClick(obj);
                    },
                    isActionable: true // 去掉点击的边框
                }
            );
        // 圆形Circle/椭圆Ellipse
        this.myDiagram.nodeTemplateMap.add("oval",
            $(go.Node, "Spot",
                { mouseEnter: this.mouseEnter }, // 线的鼠标移入事件
                $(go.Shape, "Ellipse",
                    {
                        name: 'SHAPE',
                        strokeWidth: 2,
                        stroke: this.stroke,
                        fill: this.fill
                    },
                    new go.Binding("width", "width"),
                    new go.Binding("height", "height")
                ),
                $(go.TextBlock,
                    {
                        stroke: this.color,
                        margin: 5
                    },
                    new go.Binding('text', 'name')
                ),
                {
                    click: (ev, obj) => {
                        this.categoryClick(obj);
                    },
                    isActionable: true // 去掉点击的边框
                }
            )
        );
        // 菱形
        this.myDiagram.nodeTemplateMap.add("diamond",
            $(go.Node, "Spot",
                { mouseEnter: this.mouseEnter }, // 线的鼠标移入事件
                $(go.Shape, "Diamond",
                    {
                        name: 'SHAPE',
                        strokeWidth: 2,
                        stroke: this.stroke,
                        fill: this.fill
                    },
                    new go.Binding("width", "width"),
                    new go.Binding("height", "height")
                ),
                $(go.TextBlock,
                    {
                        stroke: this.color,
                        margin: 5
                    },
                    new go.Binding('text', 'name')
                ),
                {
                    click: (ev, obj) => {
                        this.categoryClick(obj);
                    },
                    isActionable: true // 去掉点击的边框
                }
            )
        );
        // 箭头线
        this.myDiagram.linkTemplate =
            $(go.Link,
                {
                    selectable: false, // 用户不能选择链接
                    routing: go.Link.AvoidsNodes,
                    curve: go.Link.JumpGap,
                    corner: 20,
                    reshapable: true,
                    toShortLength: 7
                },
                new go.Binding('points').makeTwoWay(),
                $(go.Shape, { isPanelMain: true, stroke: this.stroke, strokeWidth: 3, name: 'WRAP' }),
                $(go.Shape, { isPanelMain: true, stroke: this.stroke, strokeWidth: 1, name: 'PIPE' }),
                $(go.Shape, { toArrow: 'Triangle', fill: this.stroke, stroke: null, name: 'ARROW' }),
                // 路径线上的文字
                $(go.TextBlock,
                    {
                        stroke: this.color,
                        font: "bold 20px '微软雅黑'",
                        margin: 5
                    },
                    new go.Binding("text", "remark")
                )
            );

        this.eachLoop(this.myDiagram);
        this.myDiagram.model = $(go.TreeModel, {
            copiesArrays: true,
            copiesArrayObjects: true,
            nodeDataArray: this.flowCharList
        });
        // 默认第一个非操作的节点高亮
        this.nodeLight($, this.flowCharList[0].key, 'on', this.blue1, this.blue2);
        // 还原旧数据
        for (const item of this.recoveryData) {
            if (item.child) { // 平级node
                for (const list of item.child.split(',')) {
                    if (!item.trueKey && !item.falseKey) {
                        this.nodeLight($, item.key, 'on', this.green1, this.green2);
                        this.nodeLight($, list.child, 'on', this.green1, this.green2);
                    } else {
                        this.nodeLight($, item.key, 'on', this.green1, this.green2);
                        if (item.trueKey) {
                            this.updateBindings(item.trueKey, '是');
                        }
                        if (item.falseKey) {
                            this.updateBindings(item.falseKey, '否');
                        }
                    }
                }

            } else { // 父子node
                if (!item.trueKey && !item.falseKey) {
                    this.nodeLight($, item.key, 'on', this.blue1, this.blue2);
                } else {
                    this.nodeLight($, item.key, 'on', this.green1, this.green2);
                    if (item.trueKey) {
                        this.updateBindings(item.trueKey, '是');
                    }
                    if (item.falseKey) {
                        this.updateBindings(item.falseKey, '否');
                    }
                }
            }
        }
    }
    // 显示点击当前节点的描述
    mouseEnter(e, link) {
        const describe = document.getElementById('describe');
        if (link.data.describe) {
            describe.innerHTML = '【' + link.data.name + '】<br/>' + link.data.describe;
            describe.style.display = 'block';
        } else {
            describe.innerHTML = '';
            describe.style.display = 'none';
        }
    }
    // 形状点击
    categoryClick(obj) {
        this.clickObj = obj;
        if (obj.data.child !== '0' || obj.data.trueKey || obj.data.falseKey) {
            this.operaStatus = this.clickObj.data.greater || this.clickObj.data.equal || this.clickObj.data.less ? true : false;
            this.Visible = true;
            this.popInput = '';
            this.popText = obj.data.name;
        }
    }
    // 找出node的obj高亮
    nodeLight($, index, type, bg1, bg2) {
        this.myDiagram.nodes.each((node) => {
            if (node.data.key === index) {
                this.nodeColor($, node, index, type, bg1, bg2);
                return;
            }
        });
    }
    // 高亮颜色
    nodeColor($, obj, step, type, bg1, bg2) {
        let wrapColor = this.arrow;
        let pipeColor = '#fff';
        let pipeArray = [10, 10];
        let arrowColor = this.arrow;
        let brosh = $(go.Brush, 'Linear', { start: go.Spot.Top, end: go.Spot.Bottom, 0: bg1, 1: bg2 });
        const shape = obj.findObject('SHAPE');

        switch (type) {
            case 'on':
                shape.stroke = brosh;
                shape.fill = brosh;
                break;
            case 'off':
                brosh = this.stroke;
                wrapColor = this.stroke;
                pipeColor = this.stroke;
                pipeArray = [];
                arrowColor = this.stroke;
                shape.stroke = this.stroke;
                shape.fill = this.fill;
                break;
        }
        // 线和箭头颜色
        this.myDiagram.links.each((link) => {
            if (link.data.key === step) {
                const wrap = link.findObject('WRAP');
                const pipe = link.findObject('PIPE');
                const arrow = link.findObject('ARROW');
                wrap.stroke = wrapColor;
                pipe.stroke = pipeColor;
                pipe.strokeDashArray = pipeArray;
                arrow.fill = arrowColor;
            }
        });
    }
    // 流动效果
    eachLoop(myDiagram) {
        const diagram = myDiagram;
        setTimeout(() => {
            const oldskips = diagram.skipsUndoManager;
            diagram.skipsUndoManager = true;
            diagram.links.each((link) => {
                const shape = link.findObject('PIPE');
                const off = shape.strokeDashOffset - 2;
                shape.strokeDashOffset = (off <= 0) ? 20 : off;
            });
            diagram.skipsUndoManager = oldskips;
            this.eachLoop(diagram);
        }, 100);
    }
    // 更新node的text
    updateBindings(key, text) {
        for (const item of this.flowCharList) {
            if (item.key === key) {
                const nodeData = this.myDiagram.model.findNodeDataForKey(key);
                nodeData.remark = text;
                this.myDiagram.model.updateTargetBindings(nodeData);
                break;
            }
        }
    }
    // 算式判断逻辑
    operation() {
        if (this.popInput || this.popInput === 0) {
            const data = this.clickObj.data;
            let operation = '0';
            if (data.greater) {
                // 大于greater 
                operation = this.popInput > Number(data.greater) ? '1' : '0';
                // 大于等于greater
                if (data.equal) {
                    operation = this.popInput === Number(data.equal) || this.popInput > Number(data.greater) ? '1' : '0';
                }
            }
            if (data.equal && !data.greater && !data.less) {
                // 等于equal 
                operation = this.popInput === Number(data.equal) ? '1' : '0';
            }
            if (data.less) {
                // 小于less 
                operation = this.popInput < Number(data.less) ? '1' : '0';
                // 小于等于less
                if (data.equal) {
                    operation = this.popInput === Number(data.equal) || this.popInput < Number(data.less) ? '1' : '0';
                }
            }
            // 大于less且小于greater
            if (data.greater && data.less) {
                operation = this.popInput < Number(data.greater) && this.popInput > Number(data.less) ? '1' : '0';
            }
            this.condition(operation);
        } else {
            this.msg.error('请输入数值');
        }
    }
    // 是否判断逻辑
    condition(type) {
        const $ = go.GraphObject.make;
        const data = this.clickObj.data;
        this.cid = [];
        this.getNode(data.key);
        // 清除所有子node高亮
        for (const item of this.cid) {
            this.nodeLight($, item.key, 'off', this.green1, this.green2);
            this.updateBindings(item.key, '');
            this.updateBindings(item.falseKey, '');
            this.updateBindings(item.trueKey, '');
        }
        switch (type) {
            case true:
                this.moreNode();
                this.nodeLight($, data.trueKey, 'on', this.blue1, this.blue2);
                this.updateBindings(data.trueKey, '是');
                break;
            case false:
                this.nodeLight($, data.falseKey, 'on', this.blue1, this.blue2);
                this.updateBindings(data.falseKey, '否');
                break;
            case '1':
                this.moreNode();
                this.nodeLight($, data.trueKey, 'on', this.blue1, this.blue2);
                this.updateBindings(data.trueKey, this.popInput);
                break;
            case '0':
                this.nodeLight($, data.falseKey, 'on', this.blue1, this.blue2);
                this.updateBindings(data.falseKey, this.popInput);
                break;
        }
        // 当前node及上面线的颜色
        this.nodeColor($, this.clickObj, data.key, 'on', this.green1, this.green2);
        this.Visible = false;
    }
    // 多级子node并行
    moreNode() {
        const child = this.clickObj.data.child;
        if (child.indexOf(',') !== -1) {
            for (const item of child.split(',')) {
                this.nodeLight(go.GraphObject.make, item, 'on', this.blue1, this.blue2);
                this.nodeColor(go.GraphObject.make, this.clickObj, item, 'on', this.green1, this.green2);
            }
        }
    }
    // 找子id
    getNode(key) {
        for (const item of this.flowCharList) {
            if (item.parent === key) {
                this.cid.push(item);
                this.getNode(item.key);
            }
        }
    }
    Cancel() {
        this.Visible = false;
    }
}
